package rf.vir


class UserController {

    def index() {
		render(view: "login")
	}
	
	def login(LoginCommand cmd) {
		if(request.method == 'POST') {
			if(cmd.validate()) {
				session.user = cmd.getUser()
				redirect controller:'main'
			} else {
				render(view: "login", model: [loginUser: cmd])
			}
		}
	}
	
	def register() {
		if(request.method == 'POST') {
			def u = new User()
			u.properties['email', 'password'] = params
			if(u.password != params.confirm) {
				u.errors.rejectValue("password", "user.password.dontmatch")
				render(view: "login", model: [user: u])
			} else {
				u.registrationDate = new Date()
				if(u.save()) {
					session.user = u
					redirect controller:"main"
				} else {
					render(view: "login", model: [user: u])
				}
			}
		}
	}
	
	def profile(ProfileChangeCommand cmd) {
		if(session.user != null) {
		
			if(request.method == 'POST') {
				cmd.user = session.user
				if(cmd.validate()) {
					def u = User.findByEmail(session.user.email)
					u.password = cmd.newPassword
					if(u.save()) {
						redirect (controller:'user', action: 'profile' )
					}
	
					render(view: "profile", model: [user: cmd])
				} else {
					render(view: "profile", model: [user: cmd])
				}
			}
		
			User user = session.user
			def ticketList = Ticket.findAllByUser(user)
		
			render(view: "profile", model: [user: user, tickets: ticketList])
		} else {
			render "Csak bejelentkezett felhasználók számára elérhető "
		}
	}
	
	def logout() {
		session.user = null
		
		redirect controller:'main'
	}
}
